const app = getApp();
const getlogininfo = require('../../getlogininfo');
const liveroom = require('../../utils/liveroom.js');
const { config } = require('../../../common/utils/ws/ws-config.js');
let listIntval = null;

Page({
  data: {
    listArray: [],
    isAnchor: 0, // 默认不是主播
    swiperCurrent: 0,
    advLists: [],
    isGetLoginInfo: false,
    supportChat: false,
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    titleBarHeight: 0,
    isServer: false, //验证服务
    floatItems:[{
      type: 0, // 页面跳转
      show: true,
      iconClass:'icon icon-sy',
      event: 'myEent1'
    },{
      type: 0, // 自定义事件
      show: true,
      iconClass: 'icon icon-live_icon',
      event: 'myEent2',
    },{
      type: 0, // 自定义事件
      show: true,
      iconClass: 'icon icon-rl',
      event: 'myEent3',
    }]
  },
  onLoad() {
    // 测试直播服务是否开启
    this.checkNode();
  },
  // 测试直播服务是否开启
  checkNode(){
    app.util.request({
      url:'entry/wxapp/index',
      data:{
        op:'checkNode',
        uniacid: `${config.uniacid}`
      },
      module:'cm_trtc',
      success: res=>{
        let { errno, data:{msg: errMsg} } = res.data;
        if(errno) {
          wx.showModal({
            title: '提示',
            content: errMsg,
            showCancel: false,
            success: res =>{
              wx.navigateBack({});
            }
          })
          return;
        } else {
          this.setData({
            isServer: true
          })
          this.onShow();
    this.getAdvLists();
        }
      }
    })
  },
  onReady: function () {
    wx.getSystemInfo({
      success: res => {
        // wx.showModal({
        //   title: '提示',
        //   content: res.model,
        //   showCancel: false,
        // });
        if (!this.data.useTabbar) {
          titleBarHeight = 0;
        }
        var titleBarHeight = res.model.indexOf('iPhone X') !== -1 ? 190 : 110;
        
        this.setData({
          titleBarHeight: titleBarHeight,
        });
      },
    });
    this.isChatSupport().then((supportChat) => {
      this.setData({ supportChat });
      if (supportChat) {
    getlogininfo.getLoginInfo({
      type: 'live_room',
          success: (ret) => {
        this.setData({
          isGetLoginInfo: true,
        });
      },
          fail: (ret) => {
            this.setData({
              isGetLoginInfo: false,
            });
        wx.showModal({
          title: '提示',
          content: ret.errMsg,
          showCancel: false,
        });
      },
    });
      } else {
        this.setData({
          isGetLoginInfo: true,
        });
      }
    });
  },

  isChatSupport() {
    return new Promise((resolve, reject) => {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'is_chat',
        },
        module: 'cm_lvb',
        success: (res) => {
          resolve(res.data && res.data.data && res.data.data.is_chat == 1);
        },
        fail: () => {
          resolve(false);
        },
      });
    });
  },
  
  onShow() {
    let { isServer } = this.data;
    if(isServer){
    this.checkAnchor();
    this.getRoomList();
    listIntval = setInterval(() => {
      this.checkAnchor();
      this.getRoomList();
    }, 5000);
    }
  },

  onHide() {
    console.log('index onHide');
    clearInterval(listIntval);
  },
  onUnload() {
    console.log('index onHide');
    clearInterval(listIntval);
    if (this.data.supportChat) {
    liveroom.logout();
    }
  },
  getRoomList() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'getRoomLists',
      },
      module: 'cm_lvb',
      success: (res) => {
        console.log('==========index getRoomList',res);
        this.setData({
          listArray: (res.data.data && res.data.data.lists) || [],
        });
      },
    });
  },
  setKeyWord(e) {
    console.log(e);

    this.setData({
      keyWord: e.detail.value,
    });
  },
  onPullDownRefresh() {
    this.checkAnchor();
    this.getRoomList();
    this.getAdvLists();
    wx.stopPullDownRefresh();
  },
  toLiveRoom(e) {
    let {
      avatar = '',
      anchor = '',
      title = '',
      playdomain = '',
      playdomain_high = '',
      id = '',
      roomid = '',
      group_id: groupID = '',
      cover: roomBackground ='',
    } = e.currentTarget.dataset.item;
    if (!playdomain && !playdomain_high) {
      wx.showModal({
        title: '系统提示',
        content: '当前房间不可进入,请稍后再试',
        showCancel: false,
        success: (res) => {
          wx.navigateTo({});  // 预创建失败直接返回上一页
        },
      });
      return;
    }
    
    if (!this.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }

    wx.navigateTo({
      url:  `/cm_lvb/pages/play/play?title=${title}&avatar=${avatar}&anchor=${anchor}&playdomain=${playdomain}&playdomainHigh=${playdomain_high}&id=${id}&roomid=${roomid}&groupID=${groupID}&roomBackground=${roomBackground}`,
    });
  },
  toUserCenter() {
    if (!this.data.isGetLoginInfo) {
      wx.showModal({
        title: '提示',
        content: '登录信息初始化中，请稍后再试',
        showCancel: false,
      });
      return;
    }
    
    wx.navigateTo({
      url: '/cm_lvb/pages/studio/studio',
    });
  },
  checkAnchor() {
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'checkAnchor',
      },
      module: 'cm_lvb',
      success: (res) => {
        let { floatItems } = this.data
        floatItems[1].show = (res.data.data && res.data.data.is_anchor)? true: false
        this.setData({
          isAnchor: (res.data.data && res.data.data.is_anchor) || 0,
          floatItems,
        });
      },
      fail: (res) => {
        let { floatItems } = this.data
        floatItems[1].show = false;
        this.setData({
          isAnchor: 0,
          floatItems,
        });
      },
    });
  },
  swiperChange(e) {
    this.setData({
      swiperCurrent: e.detail.current,
    });
  },
  getAdvLists(){
    app.util.request({
      url: 'entry/wxapp/index',
      data: {
        op: 'getAdvLists',
      },
      module: 'cm_lvb',
      success: (res) => {
        this.setData({
          advLists: res.data.data&&res.data.data.lists,
        });
      },
    });
  },

  toLiveHistory() {
    app.util.navigateTo('cm_lvb/pages/live-history/live-hisrory');
  },
  toHome() {
    const isCompanyCloudTemplate = Number(app.siteInfo.isCloudTemplate) === 1;
    if (isCompanyCloudTemplate) {  // 企业云端发布
      app.util.navigateTo('ws_micro_company_collection/pages/index/index', '', true);
      return;
    }
    let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
    const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
    app.util.navigateTo(url, {}, 'all');
  },
  onShareAppMessage() {},
});
